<?php

namespace app\admin\model;

use app\admin\model\system\SystemUser;
use app\common\basic\BaseModel;
use app\common\model\SystemRegion;

/**
 * 部门模型
 */
class Company extends BaseModel
{
    /**
     * 数据表主键
     * @var string
     */
    protected $pk = 'id';
    protected $table = 'vk_company';
    
    
    public function getAreaAttr($value, $data)
    {
        // 根据省市区id获取名称
        $regionData = SystemRegion::whereIn('id', [$data['province_id'], $data['city_id'], $data['area_id']])->column('name', 'id');
        $regionNames = [];
        if (!empty($regionData[$data['province_id']])) {
            $regionNames[] = $regionData[$data['province_id']];
        }
        if (!empty($regionData[$data['city_id']])) {
            $regionNames[] = $regionData[$data['city_id']];
        }
        if (!empty($regionData[$data['area_id']])) {
            $regionNames[] = $regionData[$data['area_id']];
        }
        return implode('-', $regionNames);
    }
    public function searchNameAttr($query, $value)
    {
        return $query->whereLike('name|short_name', "%$value%");
    }
    
    public function searchShortNameAttr($query, $value)
    {
        return $query->whereLike('short_name', "%$value%");
    }
    
    public function searchContactAttr($query, $value)
    {
        return $query->whereLike('contact|phone|email', "%$value%");
    }
    
    public function searchPhoneAttr($query, $value)
    {
        return $query->whereLike('phone', "%$value%");
    }
    
    public function user()
    {
        return $this->hasMany(CompanyUser::class, 'company_id', 'id');
    }
    
    public function business()
    {
        return $this->hasOne(SystemUser::class, 'id', 'business_manager')->field('id,username,nickname,avatar');
    }
    
    public function operation()
    {
        return $this->hasOne(SystemUser::class, 'id', 'operation_manager')->field('id,username,nickname,avatar');
    }
    
    public function project()
    {
        return $this->hasOne(SystemUser::class, 'id', 'project_manager')->field('id,username,nickname,avatar');
    }
    
}